package IOStream;

/*
 * Author: JacksonCoder
 * FileName: ConsoleToFile
 * Version: 1.0.0
 * Date: 2025/2/26
 */

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class ConsoleToFile {

    public static void main(String[] args) {
        String filePath = "source.txt"; // 输出文件路径

        // 创建Scanner 对象读取控制台输入
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入内容（输入‘exit’ 结束）：");

        // 使用 try-with-resources 自动关闭流
        try (FileWriter fw = new FileWriter(filePath);
             BufferedWriter bw = new BufferedWriter(fw)) {

            while (true) {
                String input = scanner.nextLine();
                if ("exit".equalsIgnoreCase(input)) {
                    break; // 如果用户输入 “Exit”  则退出循环
                }
                bw.write(input);
                bw.newLine();// 写入换行符
            }
            System.out.println("内容已写入文件");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            scanner.close();
        }


    }

}
